package se.plingapp.enterprisebeans;

import java.util.List;
import javax.persistence.EntityManager;

/**
 * Abstract facade with support for common operations such as
 * create, edit, remove, find and count.
 *
 * @author Jens Ljungblad
 */
public abstract class AbstractFacade<T> {

    /**
     * The class name, used for entity finding.
     */
    private Class<T> entityClass;

    /**
     * Constructor.
     *
     * @param entityClass
     */
    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    /**
     * This method needs to return an entity manager instance.
     */
    protected abstract EntityManager getEntityManager();

    /**
     * Persist the entity.
     *
     * @param entity
     */
    public T create(T entity) {
        getEntityManager().persist(entity);
        return entity;
    }

    /**
     * Merge changes to the entity.
     *
     * @param entity
     */
    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    /**
     * Remove the entity.
     *
     * @param entity
     */
    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    /**
     * Find an entity given an id.
     *
     * @param id
     */
    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    /**
     * Find all entities.
     */
    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    /**
     * Find all entities that fits in the given range.
     *
     * @param range
     */
    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    /**
     * Count the number of persisted entities.
     */
    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}